package user;

import utils.JsonOut;
import utils.MysqlUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "LoginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String email = request.getParameter("email");
        String psw = request.getParameter("password");
//        String verify = request.getParameter("verify");

        HttpSession session = request.getSession();
//        String captcha = session.getAttribute("validation_code").toString();
        PrintWriter out = response.getWriter();
        if (email == null || email.isEmpty()){
            out.println(JsonOut.error(201, "email_empty"));
            return;
        }
        if (psw == null || psw.isEmpty()){
            out.println(JsonOut.error(201, "psw_empty"));
            return;
        }

        // 验证码忽略大小写
//        verify = verify.toLowerCase();
//        captcha = captcha.toLowerCase();
//        if (!verify.equals(captcha)){
//            out.println(JsonOut.error(103, "not_verify"));
//            return;
//        }

        String savedPass = (new MysqlUtils()).getPassword(email);
        if (savedPass == null){
            out.println(JsonOut.error(101, "not_exist"));
            return;
        }

        if (!(new MysqlUtils()).checkPassword(psw, savedPass)){
            out.println(JsonOut.error(102, "psw_error"));
            return;
        }

        session.setAttribute("login_user_email", email);
        out.println(JsonOut.error(0, "login_success"));
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        out.println(JsonOut.error(403, "forbidden"));
    }
}
